<div id="formDiv"></div>
<script type="text/html" id="formContent">
  <form
    lay-filter="finishedOrderForm"
    id="finishedOrderForm"
    class="layui-form open-form"
  >
    <div class="open-model">
      <div class="open-auto">
        <div class="layui-form-item layui-row">
          <input name="id" type="hidden" />
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">销售类型</label>
            <div class="layui-input-block">
              <select
                id="selType"
                lay-search=""
                name="selType"
                lay-filter="selType"
              ></select>
            </div>
          </div>
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">客户类型</label>
            <div class="layui-input-block">
              <select
                id="customerType"
                name="customerType"
                lay-search=""
                lay-filter="customerType"
              ></select>
            </div>
          </div>
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">选择客户</label>
            <div class="layui-input-block">
              <select
                id="customerId"
                lay-search=""
                name="customerId"
                lay-filter="customerId"
              ></select>
            </div>
          </div>
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">级别</label>
            <div class="layui-input-block">
              <input
                type="text"
                class="layui-input adv-disable"
                id="agentCategoryName"
                disabled
                name="agentCategoryName"
              />
            </div>
          </div>
        </div>
        <div class="layui-form-item layui-row">
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label ">客户联系人</label>
            <div class="layui-input-block">
              <select
                id="contactId"
                name="contactId"
                lay-filter="contactId"
              ></select>
            </div>
          </div>
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">职务</label>
            <div class="layui-input-block">
              <input
                type="text"
                class="layui-input adv-disable"
                id="department"
                disabled
                name="department"
              />
            </div>
          </div>
          <div class="layui-inline layui-col-md3">
            <input name="checkerName" type="hidden" />
            <label class="layui-form-label">联系电话</label>
            <div class="layui-input-block">
              <input
                type="text"
                class="layui-input adv-disable"
                id="telephone"
                disabled
                name="telephone"
              />
            </div>
          </div>
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">销售员</label>
            <div class="layui-input-block">
              <input
                type="text"
                class="layui-input adv-disable"
                id="creatorName"
                disabled
                name="creatorName"
              />
            </div>
          </div>
        </div>
        <div class="layui-form-item layui-row">
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">订单审核人</label>
            <div class="layui-input-block">
              <select id="auditId" name="auditId" lay-filter="auditId"></select>
            </div>
          </div>

          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label w-auto">计划交付时间</label>
            <div class="layui-input-block" style="margin-left: 120px">
              <input
                type="text"
                class="layui-input"
                id="planOnTime"
                name="planOnTime"
              />
            </div>
          </div>
        </div>
        <div class="layui-form-item tableContent">
          <button class="layui-btn" type="button" id="Configure">
            配置销售信息
          </button>
          <table
            class="layui-table"
            id="finishedOrderFormTable"
            lay-filter="finishedOrderFormTable"
          ></table>
        </div>
      </div>
      <div class="layui-form-item text-right">
        <button
          class="layui-btn layui-btn-primary"
          type="button"
          ew-event="closeDialog"
        >
          关闭
        </button>
        <!-- {{# if(!['acceptance','details'].includes(d.eventName)){ }} -->
        <button
          class="layui-btn"
          lay-filter="inquiryOrderInformationSubmit"
          type="button"
          lay-submit
        >
          提交
        </button>
        <!-- {{# } }} -->
      </div>
    </div>
  </form>
</script>

<script type="text/html" id="finishedOrderFormTableBar">
  <!--    <button class="layui-btn layui-btn-xs" lay-event="accept" type="button">受理/评审</button>-->
  <!--    <button class="layui-btn layui-btn-xs" lay-event="acceptDetail" type="button">查看详情</button>-->
  <button
    class="layui-btn layui-btn-danger layui-btn-xs"
    lay-event="del"
    type="button"
  >
    删除
  </button>
</script>
<script>
  layui.use(
    ["layer", "form", "table", "admin", "laydate", "upload", "laytpl"],
    async function () {
      var $ = layui.jquery;
      var layer = layui.layer;
      var form = layui.form;
      var table = layui.table;
      var config = layui.config;
      var admin = layui.admin;
      var upload = layui.upload;
      let laydate = layui.laydate;
      let laytpl = layui.laytpl;
      const nowData = { ...parentData };

      let data = nowData?.data;
      laytpl(formContent.innerHTML).render({ ...nowData }, function (html) {
        $("#formDiv").after(html);
      });
      await admin.getDictListPro("selType", "sales_type", "销售类型");
      await admin.getDictListPro("customerType", "customer_type", "客户类型");
      await admin.initDataSelectPro(
        "user/admin/user/list",
        { limit: 999999 },
        "auditId",
        "订单审核人",
        null,
        "username,nickname"
      );

      await admin.initDataSelectPro(
        "enterprise/sell/admin/customersInfo/list",
        { limit: 999 },
        "customerId",
        "客户名称",
        async (d, obj) => {
          form.val("finishedOrderForm", {
            contactId: "",
            telephone: "",
            department: "",
            agentCategoryName: "",
          });
          form.val("finishedOrderForm", {
            agentCategoryName: obj?.agentCategoryName,
          });
          await admin.initDataSelectPro(
            "enterprise/sell/admin/contactInfo/list",
            { selCustomerId: d.value },
            "contactId",
            "客户联系人",
            (d, obj) => {
              form.val("finishedOrderForm", {
                telephone: "",
                department: "",
              });
              form.val("finishedOrderForm", {
                telephone: obj.telephone,
                department: obj.department,
              });
            }
          );
        },
        "customerName"
      );
      laydate.render({
        elem: "#planOnTime",
        type: "datetime",
      });
      const tableVal = table.render({
        elem: "#finishedOrderFormTable",
        page: false,
        limit: 999999,
        data: [],
        cols: [
          [
            { type: "numbers", title: "序号" },
            { field: "skuCode", align: "center", title: "产品SKU编号" },
            { field: "skuSpec", align: "center", title: "规格号" },
            { field: "productTypeName", align: "center", title: "产品类型" },
            { field: "mainUnitName", align: "center", title: "单位" },
            // { field: "haveQuantity", align: "center", title: "库存数" },
            {
              field: "suggestionMinPrice",
              align: "center",
              title: "建议最低单价",
            },
            {
              field: "minPrice",
              align: "center",
              title: "建议单价",
              templet: admin.setTableInput(
                "minPrice",
                nowData.eventName == "detail",
                "minPrice"
              ),
            },
            {
              field: "selQuality",
              align: "center",
              title: "销售数量",
              templet: admin.setTableInput(
                "selQuality",
                nowData.eventName == "detail",
                "selQuality"
              ),
            },
            {
              field: "totalMoney",
              align: "center",
              title: "小计金额",
            },
            {
              align: "center",
              toolbar: "#finishedOrderFormTableBar",
              hide: nowData.eventName == "detail",
              title: "操作",
              width: 200,
            },
          ],
        ],
        done: function () {
          admin.tableInputChangeByClass(
            "finishedOrderFormTable",
            "minPrice",
            (index, value, tableData, field, tableId) => {
              admin.tableProduct(
                tableId,
                index,
                ["minPrice", "selQuality"],
                "totalMoney"
              );
            }
          );
          admin.tableInputChangeByClass(
            "finishedOrderFormTable",
            "selQuality",
            (index, value, tableData, field, tableId) => {
              admin.tableProduct(
                tableId,
                index,
                ["minPrice", "selQuality"],
                "totalMoney"
              );
            }
          );
        },
      });
      if (nowData.eventName == "detail") {
        admin.setFormDisable("#finishedOrderForm", true);
      }
      if (data?.id) {
        const res1 = await admin.initDataSelectPro(
          "enterprise/sell/admin/contactInfo/list",
          { selCustomerId: nowData.data.customerId },
          "contactId",
          "客户联系人",
          (d, obj) => {
            form.val("finishedOrderForm", {
              telephone: "",
              department: "",
            });
            form.val("finishedOrderForm", {
              telephone: obj.telephone,
              department: obj.department,
            });
          }
        );
        console.log("res1", res1);
        if (res1[0]) {
          form.val("finishedOrderForm", {
            telephone: res1[0].telephone,
            department: res1[0].department,
          });
        }
        const res = await admin.reqPro(
          "enterprise/sell/admin/customersInfo/list",
          { id: nowData.data.customerId }
        );
        if (res.data[0]) {
          form.val("finishedOrderForm", {
            agentCategoryName: res.data[0].agentCategoryName,
          });
        }

        form.val("finishedOrderForm", nowData.data);

        //赋值销售信息
        let dataInfo = nowData.data.details;
        dataInfo.forEach((item) => {
          item.suggestionMinPrice = item.suggestLowestPrice;
          item.minPrice = item.price;
        });
        console.log("dataInfo", dataInfo);
        tableVal.reload({ data: dataInfo });
      } else {
        $("#creatorName").val(
          JSON.parse(localStorage.getItem("wing")).login_user.username
        );
      }

      form.on("submit(inquiryOrderInformationSubmit)", function (d) {
        let formData = { ...d.field };
        let url = "";
        let method = "";
        //修改
        if (formData.id) {
          if (nowData.eventName == "edit") {
            url = "enterprise/sell/admin/finishedOrder/update";
            method = "POST";
            formData.detailList = table.cache["finishedOrderFormTable"].map(
              (v) => {
                return {
                  id: v.id,
                  //小计金额
                  totalMoney: v.totalMoney,
                  //销售数量
                  selQuality: v.selQuality,
                  //单价
                  price: v.minPrice,
                  //物料id
                  productDetailId: v.productDetailId,
                };
              }
            );
          }
        }
        //新增逻辑
        else {
          url = "enterprise/sell/admin/finishedOrder/add";
          method = "POST";
          formData.detailList = table.cache["finishedOrderFormTable"].map(
            (v) => {
              return {
                //小计金额
                totalMoney: v.totalMoney,
                //销售数量
                selQuality: v.selQuality,
                //单价
                price: v.minPrice,
                //物料id
                productDetailId: v.productDetailId,
              };
            }
          );
        }
        admin.req(
          url,
          JSON.stringify(formData),
          function (res) {
            layer.closeAll("loading");
            if (res.code == 200) {
              layer.msg(res.msg, { icon: 1 });
              layer.closeAll();
              table.reload("finishedOrderTable");
            } else {
              layer.msg(res.msg, { icon: 2 });
            }
          },
          method,
          true,
          "application/json; charset=utf-8"
        );
        return false;
      });
      // 确保表格的工具栏事件只绑定一次

      // });
      table.on("tool(finishedOrderFormTable)", function (obj) {
        var d = obj.data; // 获取当前行的数据
        var layEvent = obj.event; // 获取事件名（edit 或 del）
        if (obj.tr) {
          obj.tr.on("click", function (e) {
            e.preventDefault(); // 防止默认行为
          });
        }
        if (layEvent == "del") {
          const index = $(obj.tr[0]).data("index");
          let list = table.cache["finishedOrderFormTable"].filter((v) => {
            return v["LAY_TABLE_INDEX"] != index;
          });
          table.reload("finishedOrderFormTable", {
            data: list,
          });
        }
        // else if (layEvent == 'accept' || layEvent == 'acceptDetail') {
        //     admin.formOpen({
        //         area: ['70%', '85%'],
        //         offset: ['50px', '15%'],
        //         title: '受理/评审详情',
        //         path: 'components/sell/orderFormAccept.html',
        //         success: function () {
        //             parentData.orderObj = d
        //             parentData.data = data
        //             parentData.eventName = layEvent
        //         }
        //     })
        // } else if (layEvent == 'quotationRecord') {
        //
        // }
      });
      $("#Configure").click(function () {
        admin.formOpen({
          area: "90%",
          offset: "50px",
          title: "配置订单物料信息",
          // path: 'components/sell/finishedOrderFormTable.html',
          path: "components/purchase/skuTableForm.html",
          success: function () {
            parentData.cacheList = [...table.cache["finishedOrderFormTable"]];
            if (parentData.cacheList.length > 0) {
              parentData.notInListIds = parentData.cacheList
                .map((v) => v.productDetailId)
                .join();
            } else {
              parentData.notInListIds = "";
            }
            // console.log(123,table.cache['finishedOrderFormTable'])
          },
          end: function () {
            if (childData.list) {
              const newData = childData.list || [];
              const oldData = table.cache["finishedOrderFormTable"];
              const list = [...oldData, ...newData];
              table.reload("finishedOrderFormTable", {
                data: list, // 设置新的数据
              });
            }
          },
        });
      });
    }
  );
</script>
<style>
  #finishedOrderForm .layui-form-item .layui-inline {
    /* margin-bottom: 5px; */
    margin-right: 0px;
  }
</style>
